<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.view' );

class WrdViewReports extends WrdView{

	function display($tpl = null) {
		$this->setModel($this->getModel('reports'), true);
		$fnc = 'display'.ucfirst($this->getLayout());
		if (is_callable(array(&$this, $fnc)))
			$this->$fnc($tpl);
		else
			parent::display($tpl);
	}

	function displayDefault($tpl = null){
		$user = &JFactory::getUser();
		$document = & JFactory::getDocument();
		$view = JRequest::getCmd('view');
		$mainframe = JFactory::getApplication();
		//anne chau
		$mainframe->redirect('index.php?option=com_wrd&controller=reports&layout=memberpendingreportsum');
		
		$document->setTitle( JText::_('Reports') );
		WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
	    
		JToolBarHelper::title(JText::_('Reports'),'member_ship_reports.png');
		
		if($user->authorise('wrd.dashboard.admin', 'com_wrd'))
			JToolBarHelper::preferences('com_wrd','wrdreport', '600');

		parent::display($tpl);
  	}
  	
    function displayTransaction($tpl = null){

        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        
        WrdHelper::addSubMenu($view,$this->getLayout());
        /********* SET DATA *********/
        $document->setTitle( JText::_('Transaction Reports') );        
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Membership Reports'),'reports.png');
        JToolBarHelper::custom('exportexcel','excel','excel','Excel',false);
        
        /********* GET DATA FROM DATABASE *********/
        $model    = &$this->getModel();
        
        //get list items
        $items      = $model->getTransaction(1);
        $paging     = $model->getPaging($model->getTransaction(0));

        $lists['order']         = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
        $lists['order_Dir']     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
        
        
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
       
        $this->assignRef('pagination',    $paging);
               
        parent::display($tpl);
    }
    
    /*
     *  Redemption Report
     */     
    function displayRedemptionreport($tpl = null)
    {
    	$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.giftsredemption', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
        
        /******** Save pick up date, Deliver to outlet Date ********/        
        if($task == 'updateDateRedemption')
        {
            $result = array();
            $queryString['id'] = intval($_POST['id']);
            $queryString['d'] = strval($_POST['d']);
            $queryString['type'] = strval($_POST['t']);
            
            $result['success'] = $model->updateRedemptionDate($queryString); 
            if($result['success'])
            {
                $result['html'] = $queryString['d'];
            } 
            $result = json_encode($result);
            echo "({$result})";
            exit;
        }
        
        /******** Filter field ********/        
        $extra_filter_field     = $mainframe->getUserStateFromRequest( $context.$view.'extra_filter_field','extra_filter_field','','string' );              
        $lists['extra_filter_field'] = JHTML::_('wrd.listFilterFieldComplain','extra_filter_field',  $extra_filter_field);
        
        
        /******** Search value ********/        
        $search_value = $mainframe->getUserStateFromRequest( $context.$view.'search_value','search_value','','string' );              
        $lists['search_value'] = $search_value;
               
        
        /******** Product ********/       
        $extra_products     = $mainframe->getUserStateFromRequest( $context.$view.'extra_products','extra_products','','array' );              
        $lists['extra_products'] = JHTML::_('wrd.listProductsFilter','extra_products[]',  $extra_products, ' multiple="multiple" size="5" ');
        
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
                
        
        /******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        
        
        /******** Status ********/
        $extra_status     = $mainframe->getUserStateFromRequest( $context.$view.'extra_status','extra_status','','string' );        
        $lists['extra_status'] = JHTML::_('wrd.redemptionStatusList','extra_status',  $extra_status); 
        
        
        /******** Filter By ********/
        $extra_filter_by     = $mainframe->getUserStateFromRequest( $context.$view.'extra_filter_by','extra_filter_by','','string' );        
        $lists['extra_filter_by'] = JHTML::_('wrd.redemptionFilterByList','extra_filter_by',  $extra_filter_by); 
        
        
        /********* CHECK DATE *********/
        if($pr['date_from'] != '') { $datefrom = explode('-', $pr['date_from']); }
        else {
            $datefrom[0] = date('Y');
            $datefrom[1] = date('m');
            $datefrom[2] = '01';
        }
        if($pr['date_to'] != '') { $dateto = explode('-', $pr['date_to']); }
        else {
            $dateto[0] = date('Y', time());
            $dateto[1] = date('m', time());
            $dateto[2] = date('d', time());
        }      
        /********* QUERY DATA *********/
        $conditions = array();
        $conditions['dateFrom'] = implode('-',$datefrom).' 00:00:00';
        $conditions['dateTo'] = implode('-',$dateto).' 23:59:59';
        
        $conditions['filter_field'] = $extra_filter_field;
        $conditions['search_value'] = trim($search_value);
        $conditions['filter'] = intval($extra_filter_by);
        
        $conditions['status'] = intval($extra_status);
        $conditions['products'] = (!empty($extra_products) ? trim(implode(',',$extra_products),',') : '');        
        $conditions['outlet'] = (!empty($filter_pick_up_outlet) ? trim(implode(',',$filter_pick_up_outlet),',') : '');
        /******** Export excel: Redemption ********/
        $params = '';
        if($task == 'exredemptionreport')
        {   
            $params .= '&df='.$conditions['dateFrom'];
            $params .= '&dt='.$conditions['dateTo'];                     
            
            $params .= '&ff='.$conditions['filter_field'];
            $params .= '&sv='.$conditions['search_value'];            
            $params .= '&f='.$conditions['filter'];
            
            $params .= '&s='.$conditions['status'];
            $params .= '&p='.$conditions['products'];
            $params .= '&o='.$conditions['outlet'];
            
            $params .= '&l='.(intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));
            //echo $params;die;
            header('Location: '.JURI::root().'/exredemptionreport.php?'.$params);            
        }
        $items      = $model->redemptionreport($conditions);   
        $paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];
       
        
        /********* SET DATA *********/
        $document->setTitle( JText::_('Redemption Report'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Redemption Report'),'reports.png');
        
        
        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('task',    $task);
        $this->assignRef('pagination', $paging);
               
        parent::display($tpl);
    }
	
    /*
     *  Redemption Report Product
     */     
    function displayRedemptionreportproduct($tpl = null)
    {
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.giftsredemption', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
		$post = JRequest::get('post');  
  
        $extra_products     = $mainframe->getUserStateFromRequest( $context.$view.'extra_products','extra_products','','array' );              
        $lists['extra_products'] = JHTML::_('wrd.listProductsFilter','extra_products[]',  $extra_products, ' multiple="multiple" size="5" ');
        
        /******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
                
        
        /********* CHECK DATE *********/
        if($pr['date_from'] != '') { $datefrom = explode('-', $pr['date_from']); }
        else {
            $datefrom[0] = date('Y');
            $datefrom[1] = date('m');
            $datefrom[2] = '01';
        }
        if($pr['date_to'] != '') { $dateto = explode('-', $pr['date_to']); }
        else {
            $dateto[0] = date('Y', time());
            $dateto[1] = date('m', time());
            $dateto[2] = date('d', time());
        }      
        /********* QUERY DATA *********/
        $conditions = array();
        $conditions['dateFrom'] = implode('-',$datefrom).' 00:00:00';
        $conditions['dateTo'] = implode('-',$dateto).' 23:59:59';
        
		$conditions['status'] = $post['status'];
		if(!isset($conditions['status'])) $conditions['status'] = 1;
        $conditions['products'] = (!empty($extra_products) ? trim(implode(',',$extra_products),',') : '');        
        $conditions['outlet'] = (!empty($filter_pick_up_outlet) ? trim(implode(',',$filter_pick_up_outlet),',') : '');
         
		 //echo '<pre>';print_r($conditions);
        /******** Export excel: Redemption ********/
        $params = '';
        if($task == 'exredempreportproduct')
        {  
			$params .= '&df='.$conditions['dateFrom'];
            $params .= '&dt='.$conditions['dateTo'];                     
            $params .= '&f='.$conditions['filter'];
            $params .= '&s='.$conditions['status'];
            $params .= '&p='.$conditions['products'];
			$params .= '&o='.$conditions['outlet'];
			
            $params .= '&l='.(intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));
            //echo $params;die;
            header('Location: '.JURI::root().'exredempreportproduct.php?'.$params);            
        }
		//print_r($conditions);
		$items      = $model->redemptionreportproduct($conditions);	
		//echo "<pre>";print_r($items );
		$paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];

        /********* SET DATA *********/
        $document->setTitle( JText::_('Redemption Report Products'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Redemption Report Products'),'reports.png');
        
        
        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr', $pr);
		$this->assignRef('status',$conditions['status']);
		$this->assignRef('outlet',$conditions['outlet']);
        $this->assignRef('task', $task);
        $this->assignRef('pagination', $paging);
               
        parent::display($tpl);
    }

    
    function displayApprovevoucher($tpl = null)
    {
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.giftsredemption', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
		$m_outlet = &JModelLegacy::getInstance('outlets','WrdModel');
		$outlet = $m_outlet->getList($condition = 'and cid = 01');
		$post = JRequest::get('post');  
		
		$conditions['sredem'] = $post['sredem'];
		$conditions['member_id'] = $post['member_id'];
		$conditions['code_voucher'] = $post['code_voucher'];
		$conditions['status'] = $post['status'];
		
		$items = $model->approveVoucher($conditions);
		$paging     = $model->getPaging($items['total']);   
        
		$items      = $items['items'];
		
        $document->setTitle( JText::_('Approve Voucher'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Approve Voucher'),'free_gift.png');
		
		$this->assignRef('outlet',$outlet);
        $this->assignRef('items',$items);
		$this->assignRef('status',$post['status']);
		$this->assignRef('member_id',$post['member_id']);
		$this->assignRef('code_voucher',$post['code_voucher']);
        $this->assignRef('sredem',$post['sredem']);
        $this->assignRef('pagination', $paging);
        parent::display($tpl);
	}
 
    function displayRedemptionreportvoucher($tpl = null)
    {
    
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.giftsredemption', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
		$post = JRequest::get('post');
		
        /******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        
		/******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
        
		$pr['date_from_redem'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from_redem','date_from_redem','','date' );
        $pr['date_to_redem']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to_redem','date_to_redem','','date' );
		
		
		$conditions = array();
        
		if($pr['date_from'] != '') { $conditions['dateFrom'] = $pr['date_from'].' 00:00:00'; }
        else $conditions['dateFrom'] = '';
        if($pr['date_to'] != '') { $conditions['dateTo'] = $pr['date_to'].' 23:59:59';}
        else $conditions['dateTo'] = '';
		
		if($pr['date_from_redem'] != '') { $conditions['dateFromredem'] = $pr['date_from_redem'].' 00:00:00'; }
        else $conditions['dateFromredem'] = '';
        if($pr['date_to_redem'] != '') { $conditions['dateToredem'] = $pr['date_to_redem'].' 23:59:59';}
        else $conditions['dateToredem'] = '';
        $conditions['status'] = $post['status'];
		
		$conditions['outlet'] = (!empty($filter_pick_up_outlet) ? trim(implode(',',$filter_pick_up_outlet),',') : '');
        /******** Export excel: Redemption ********/
        $params = '';
		
		if($task == 'exredempvoucher')
        {   
			$params .= '&df='.$conditions['dateFrom'];
            $params .= '&dt='.$conditions['dateTo']; 
			$params .= '&dfr='.$conditions['dateFromredem'];
            $params .= '&dtr='.$conditions['dateToredem']; 			
            $params .= '&s='.$conditions['status'];
			$params .= '&o='.$conditions['outlet'];
            header('Location: '.JURI::root().'exredempvoucher.php?'.$params);            
        }

		$items = $model->redemptionreportvoucher($conditions);
		
		$paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];
        $document->setTitle( JText::_('Redemption Report Voucher'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Redemption Report Voucher'),'reports.png');

        $this->assignRef('lists',    $lists);
		$this->assignRef('items',$items);
		$this->assignRef('status',$conditions['status']);
		$this->assignRef('pr',    $pr);
		$this->assignRef('topDisplay', $post['topDisplaySelect']);
		$this->assignRef('pagination', $paging);
               
        parent::display($tpl);
    }
    
	function displayMemberstatisticjob($tpl = null)
    {
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.member', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
      
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
		$post = JRequest::get('post');
		
        $listIndustry     = $mainframe->getUserStateFromRequest( $context.$view.'listIndustry','listIndustry','','array' );              
        $lists['listIndustry'] = JHTML::_('wrd.listIndustryReport','listIndustry[]',$listIndustry,'','listIndustry','' );
		
		$department     = $mainframe->getUserStateFromRequest( $context.$view.'department','department','','array' );              
        $lists['department'] = JHTML::_('wrd.listDepartmentReport','department[]',$department,'','department','' );
		
		$listJob     = $mainframe->getUserStateFromRequest( $context.$view.'listJob','listJob','','array' );              
        $lists['listJob'] = JHTML::_('wrd.listJobReport','listJob[]',$listJob,'','listJob','' );
		
		$conditions['listIndustry'] = (($listIndustry[0] != 0) ? trim(implode(',',$listIndustry),',') : '');
        $conditions['department'] = (($department[0] != 0) ? trim(implode(',',$department),',') : '');
		$conditions['listJob'] = (($listJob[0] != 0) ? trim(implode(',',$listJob),',') : '');
        
		$params = '';
		if($task == 'exmemberstatisticjob')
        {   
			$params .= '&i='.$conditions['listIndustry'].'&j='.$conditions['listJob'].'&d='.$conditions['department'].'&limit='.$post['topDisplaySelect'];
            header('Location: '.JURI::root().'exmemberstatisticjob.php?'.$params);            
        }
		
		$items = $model->memberstatisticjob($conditions);
		$paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];
        $document->setTitle( JText::_('Member statistic On Job'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Member statistic On Job'),'reports.png');
		
        $this->assignRef('lists',    $lists);
		$this->assignRef('items',$items);
		$this->assignRef('status',$conditions['status']);
		$this->assignRef('topDisplay', $post['topDisplaySelect']);
		$this->assignRef('pagination', $paging);
         
        parent::display($tpl);
    }
    
	function displayMemberreport($tpl = null)
    {
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.member', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
		$post = JRequest::get('post');
		
		$pr = array() ;
		$pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
		
		if($pr['date_from'] != '') { $conditions['dateFrom'] = $pr['date_from'].' 00:00:00'; }
        else $conditions['dateFrom'] = date("Y-m")."-01"." 00:00:00";
        if($pr['date_to'] != '') { $conditions['dateTo'] = $pr['date_to'].' 23:59:59';}
        else $conditions['dateTo'] = date("Y-m-d")." 23:59:59";
		
		$params = '';
		if($task == 'exmemberreport')
        {   
			$params .= '&f='.$conditions['dateFrom'].'&t='.$conditions['dateTo'].'&limit='.$post['topDisplaySelect'];
            header('Location: '.JURI::root().'exmemberreport.php?'.$params);            
        }
		
		$items = $model->memberreport($conditions);
		$paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];
        $document->setTitle( JText::_('Master List Report'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Master List Report'),'reports.png');
		
		$this->assignRef('items',$items);
		$this->assignRef('pr',$pr);
		$this->assignRef('topDisplay', $post['topDisplaySelect']);
		$this->assignRef('pagination', $paging);
         
        parent::display($tpl);
    }
    
	function displayOutletreport($tpl = null)
    {
		$user  = &JFactory::getUser();
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
		$post = JRequest::get('post');
		
		$pr = array() ;
		$pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
		
		if($pr['date_from'] != '') { $conditions['dateFrom'] = $pr['date_from'].' 00:00:00'; }
        else $conditions['dateFrom'] = '';
        if($pr['date_to'] != '') { $conditions['dateTo'] = $pr['date_to'].' 23:59:59';}
        else $conditions['dateTo'] = '';
		
		$params = '';
		if($task == 'exoutletreport')
        {   
			$params .= '&f='.$conditions['dateFrom'].'&t='.$conditions['dateTo'].'&limit='.$post['topDisplaySelect'].'&baseon='.$post['baseon'];
            header('Location: '.JURI::root().'exoutletreport.php?'.$params);            
        }
		
		$items = $model->outletreport($conditions);
		$paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];
        $document->setTitle( JText::_('Summary Member Spending Report'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Summary Member Spending Report'),'reports.png');

		$this->assignRef('items',$items);
		$this->assignRef('pr',$pr);
		$this->assignRef('baseon', $post['baseon']);
		$this->assignRef('topDisplay', $post['topDisplaySelect']);
		$this->assignRef('pagination', $paging);
         
        parent::display($tpl);
    }
	
	/*
     *  Redemption Report 
     */     
    function displayRedempreport($tpl = null)
    {
		
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.giftsredemption', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
		$post = JRequest::get('post');
        
		$conditions['status'] = $post['status'];
		if(!isset($conditions['status'])) $conditions['status'] = 1;
		
		$pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
		
		if($pr['date_from'] != '') { $conditions['dateFrom'] = $pr['date_from'].' 00:00:00'; }
        else $conditions['dateFrom'] = '';
        if($pr['date_to'] != '') { $conditions['dateTo'] = $pr['date_to'].' 23:59:59';}
        else $conditions['dateTo'] = '';
		
		$conditions['outlet'] = (!empty($filter_pick_up_outlet) ? trim(implode(',',$filter_pick_up_outlet),',') : '');
        
        $params = '';
		if($task == 'exredempreport')
        {   
            $params .= '&f='.$conditions['dateFrom'].'&t='.$conditions['dateTo'].'&limit='.$post['topDisplaySelect'].'&s='.$post['status'];
			header('Location: '.JURI::root().'exredempreport.php?'.$params);            
        }
		$items = $model->redempreport($conditions);
		$paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];
        /********* SET DATA *********/
        $document->setTitle( JText::_('Redemption Report Voucher & Products'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Redemption Report Voucher & Products'),'reports.png');
		/********* RENDER *********/

		$this->assignRef('items',$items);
		$this->assignRef('pr',$pr);
		$this->assignRef('status',$conditions['status']);
		$this->assignRef('topDisplay', $post['topDisplaySelect']);
		$this->assignRef('pagination', $paging);
               
        parent::display($tpl);
    }
	function displayRedempreportdetail($tpl = null)
    {
		
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.giftsredemption', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
		$post = JRequest::get('post');
        $pr = array() ;
		$conditions['outlet'] = (!empty($filter_pick_up_outlet) ? trim(implode(',',$filter_pick_up_outlet),',') : '');
        
        $params = '';
		if($task == 'exredempreportdetail')
        {   
            header('Location: '.JURI::root().'exredempreportdetail.php');            
        }
		$items = $model->redempreportdetail($conditions);
		$paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];
        /********* SET DATA *********/
        $document->setTitle( JText::_('Redemption Report Detail Voucher & Products'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Redemption Report Detail Voucher  & Products'),'reports.png');
		
		/********* RENDER *********/
		$this->assignRef('items',$items);
		$this->assignRef('status',$conditions['status']);
		$this->assignRef('topDisplay', $post['topDisplaySelect']);
		$this->assignRef('pagination', $paging);
               
        parent::display($tpl);
    }
	
    /*
     *  Member Service Report
     */     
    function displayMemberservicereport($tpl = null)
    {
    	$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.memberservice', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
    	
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
        
        /******** Save pick up date ********/        
        if($task == 'savepickupdate')
        {
            $result = array();
            $queryString['id'] = intval($_POST['id']);
            $queryString['d'] = strval($_POST['d']);
            $result['success'] = $model->updatePickUpDate($queryString); 
            if($result['success'])
            {
                $result['html'] = $queryString['d'];
            } 
            $result = json_encode($result);
            echo "({$result})";
            exit;
        }
        
        /******** Filter field ********/        
        $extra_filter_field     = $mainframe->getUserStateFromRequest( $context.$view.'extra_filter_field','extra_filter_field','','string' );              
        $lists['extra_filter_field'] = JHTML::_('wrd.listFilterFieldComplain','extra_filter_field',  $extra_filter_field);
        
        
        /******** Search value ********/        
        $search_value = $mainframe->getUserStateFromRequest( $context.$view.'search_value','search_value','','string' );              
        $lists['search_value'] = $search_value;
        
       
        /******** Member Type ********/
        $filter_member_type     = $mainframe->getUserStateFromRequest( $context.$view.'member_type','member_type','','array' );              
        $lists['filter_member_type'] = JHTML::_('wrd.memberTypeList','member_type[]',$filter_member_type,'','member_type','','' );
        
        
        /******** Meal period ********/        
        $extra_meal_period     = $mainframe->getUserStateFromRequest( $context.$view.'extra_meal_period','extra_meal_period','','array' );              
        $lists['extra_meal_period'] = JHTML::_('wrd.listMealPeriod','extra_meal_period[]',  $extra_meal_period); 
        
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
                
        
        /******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        
        
        /******** Handle by ********/
        $filter_handle_by     = $mainframe->getUserStateFromRequest( $context.$view.'handle_by','handle_by','','string' );              
        $lists['filter_handle_by'] = JHTML::_('wrd.listHandleBy','handle_by',$filter_handle_by,'','pick_up_at','','' );
        
        
        /********* CHECK DATE *********/
        if($pr['date_from'] != '') { $datefrom = explode('-', $pr['date_from']); }
        else {
            $datefrom[0] = date('Y');
            $datefrom[1] = date('m');
            $datefrom[2] = '01';
        }
        if($pr['date_to'] != '') { $dateto = explode('-', $pr['date_to']); }
        else {
            $dateto[0] = date('Y', time());
            $dateto[1] = date('m', time());
            $dateto[2] = date('d', time());
        }
                
        /********* QUERY DATA *********/
        $conditions = array();
        $conditions['filter_field'] = $extra_filter_field;
        $conditions['search_value'] = trim($search_value);
        //$conditions['type'] = (!empty($extra_type) ? trim(implode(',',$extra_type),',') : '');
        $conditions['meal'] = (!empty($extra_meal_period) ? trim(implode(',',$extra_meal_period),',') : '');
        $conditions['dateFrom'] = implode('-',$datefrom);
        $conditions['dateTo'] = implode('-',$dateto);
        $conditions['outlet'] = (!empty($filter_pick_up_outlet) ? trim(implode(',',$filter_pick_up_outlet),',') : '');
        $conditions['handle_by'] = $filter_handle_by;
        
        if(!empty($filter_member_type)) {
            for($i=0; $i<count($filter_member_type); $i++){
                $filter_member_type[$i] = explode(', ', $filter_member_type[$i]);
                $filter_member_type[$i] = implode("', '", $filter_member_type[$i]);
            }        
            $filter_member_type = implode("', '", $filter_member_type);
        }
        $conditions['member_type'] = ($filter_member_type != '' ? "'".$filter_member_type."'" : '');
        
        
        /******** Export excel: Member Statistic ********/
        
        if($task == 'exmemberservicereport')
        {                        
            $params = 'ff='.$conditions['filter_field'];
            $params .= '&sv='.$conditions['search_value'];
            //$params .= '&t='.$conditions['type'];
            $params .= '&m='.$conditions['meal'];
            $params .= '&df='.$conditions['dateFrom'];
            $params .= '&dt='.$conditions['dateTo'];
            $params .= '&o='.$conditions['outlet'];
            $params .= '&h='.$conditions['handle_by'];
            $params .= '&l='.(intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));
            $params .= '&mt='.$conditions['member_type'];
            
            header('Location: '.JURI::root().'exmemberservicereport.php?'.$params);            
        }
        
        $items      = $model->memberServiceReport($conditions);   
        $paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];

        /********* SET DATA *********/
        $document->setTitle( JText::_('Member Service Report'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Member Service Report'),'reports.png');

        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('task',    $task);
        $this->assignRef('pagination', $paging);
               
        parent::display($tpl);
    }
    
    /*
     *  Complain Report
     */     
    function displayComplainreport($tpl = null)
    {
    	$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.complain', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
        
        /******** Filter field ********/        
        $extra_filter_field     = $mainframe->getUserStateFromRequest( $context.$view.'extra_filter_field','extra_filter_field','','string' );              
        $lists['extra_filter_field'] = JHTML::_('wrd.listFilterFieldComplain','extra_filter_field',  $extra_filter_field);
        
        
        /******** Search value ********/        
        $search_value = $mainframe->getUserStateFromRequest( $context.$view.'search_value','search_value','','string' );              
        $lists['search_value'] = $search_value;
        
        
        /******** Type ********/        
        $extra_type     = $mainframe->getUserStateFromRequest( $context.$view.'extra_type','extra_type','','array' );              
        $lists['extra_type'] = JHTML::_('wrd.listComplainType','extra_type[]',  $extra_type); 
        
        
        /******** Meal period ********/        
        $extra_meal_period     = $mainframe->getUserStateFromRequest( $context.$view.'extra_meal_period','extra_meal_period','','array' );              
        $lists['extra_meal_period'] = JHTML::_('wrd.listMealPeriod','extra_meal_period[]',  $extra_meal_period); 
        
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
                
        
        /******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        
        
        /******** Handle by ********/
        $filter_handle_by     = $mainframe->getUserStateFromRequest( $context.$view.'handle_by','handle_by','','string' );              
        $lists['filter_handle_by'] = JHTML::_('wrd.listHandleBy','handle_by',$filter_handle_by,'','pick_up_at','','' );
        
        
        /********* CHECK DATE *********/
        if($pr['date_from'] != '') { $datefrom = explode('-', $pr['date_from']); }
        else {
            $datefrom[0] = date('Y');
            $datefrom[1] = date('m');
            $datefrom[2] = '01';
        }
        if($pr['date_to'] != '') { $dateto = explode('-', $pr['date_to']); }
        else {
            $dateto[0] = date('Y', time());
            $dateto[1] = date('m', time());
            $dateto[2] = date('d', time());
        }
                
        /********* QUERY DATA *********/
        $conditions = array();
        $conditions['filter_field'] = $extra_filter_field;
        $conditions['search_value'] = trim($search_value);
        $conditions['type'] = (!empty($extra_type) ? trim(implode(',',$extra_type),',') : '');
        $conditions['meal'] = (!empty($extra_meal_period) ? trim(implode(',',$extra_meal_period),',') : '');
        $conditions['dateFrom'] = implode('-',$datefrom);
        $conditions['dateTo'] = implode('-',$dateto);
        $conditions['outlet'] = (!empty($filter_pick_up_outlet) ? trim(implode(',',$filter_pick_up_outlet),',') : '');
        $conditions['handle_by'] = $filter_handle_by;
        
        //var_dump($conditions);
        /******** Export excel: Member Statistic ********/
        if($task == 'excomplainfilter')
        {                        
            $params = 'ff='.$conditions['filter_field'];
            $params .= '&sv='.$conditions['search_value'];
            $params .= '&t='.$conditions['type'];
            $params .= '&m='.$conditions['meal'];
            $params .= '&df='.$conditions['dateFrom'];
            $params .= '&dt='.$conditions['dateTo'];
            $params .= '&o='.$conditions['outlet'];
            $params .= '&h='.$conditions['handle_by'];
            $params .= '&l='.(intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));
                   
            header('Location: '.JURI::root().'excomplainfilter.php?'.$params);            
        }
        
        
        $items      = $model->complainReport($conditions);   
       // var_dump($items['total']);
		$paging     = $model->getPaging($items['total']);   
        $items      = $items['items'];

        /********* SET DATA *********/
        $document->setTitle( JText::_('Complain Report'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Complain Report'),'reports.png');

        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('task',    $task);
        $this->assignRef('pagination', $paging);
               
        parent::display($tpl);
    }
    
    function displaySystemcheck($tpl = null)
    {
		$db = JFactory::getDbo();
		
		//check User co trong profile nhung khong co trong bang user
		$data['items1'] = "SELECT p.* FROM #__wrd_profile AS p
					 WHERE p.user_id NOT IN ( SELECT id FROM vip_users )";
		
		//Check co vip_number trong bang transachtion nhung khong co trong profile
		$data['items2'] = "SELECT t.* FROM #__wrd_transaction AS t
					 WHERE t.vip_number NOT IN ( SELECT member_id FROM #__wrd_profile )
		";
		
		//Check User co trong bang point nhung khong co trong bang profile
		$data['items4'] = "SELECT * FROM `#__wrd_point` WHERE user_id NOT IN (
			SELECT user_id FROM #__wrd_profile
		)";
	
	
		
		$data["items5"] = "SELECT * FROM #__wrd_profile GROUP BY member_id HAVING count(member_id)>1";
		
		$data["items6"] = "SELECT * FROM `#__wrd_point` as p
							 WHERE (p.type=0) AND (p.transaction IS NOT NULL) AND (p.transaction
								NOT IN (SELECT transaction_id FROM #__wrd_transaction)
							 )";
	    $data["items7"] = "SELECT * FROM `#__wrd_point` AS p
					 WHERE (p.user_id=0) OR (p.user_id IS NULL)";
						
		$data["items8"] = "SELECT * FROM #__wrd_transaction GROUP BY transaction_id HAVING count( CONCAT( transaction_id, '', outlet ) ) >1";
		
		$data["items9"] = "SELECT * FROM #__wrd_profile GROUP BY p_email HAVING count(p_email)>1";
		
		
		$document = & JFactory::getDocument();
		$document->setTitle( JText::_('System Check'));        
		WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
		JToolBarHelper::title(JText::_('System Check'),'systemcheck.png');
		$this->assignRef('data', $data);
		parent::display($tpl);
	}
	/*
     *  Windsor VIP Member Birthday
     */     
    function displayMemberbirthday($tpl = null)
    {
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.member', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));

        /********* INIT *********/
        $mainframe 	= &JFactory::getApplication();
        $document 	= &JFactory::getDocument();
        $context 	= &JRequest::getCmd('option');
        $view 		= &JRequest::getCmd('view');
        $task 		= &JRequest::getCmd('task');
        $model    	= &$this->getModel();
        $post 		= &JRequest::get('post');
		/******** Calendar ********/
        $pr = array() ;
		
		$conditions['dateFrom'] = empty($post['date_from'])?date('d-m', mktime(0, 0, 0, date('m'), 1)):$post['date_from'];
        $conditions['dateTo'] = empty($post['date_to'])?date('d-m', mktime(0, 0, 0, date('m'), 31)):$post['date_to'];
		$conditions['topDisplaySelect'] = $post['topDisplaySelect'];

        if($task == 'exmemberbirthday'){                        
			$params .= '&df='.$conditions['dateFrom'];
            $params .= '&dt='.$conditions['dateTo'];
			$params .= '&l='.intval($_POST['topDisplaySelect']);
            header('Location: '.JURI::root().'/exmemberbirthday.php?'.$params);            
        }

        $data = $model->memberbirthday($conditions);       
        $paging     = $model->getPaging($data['total']);   

        $document->setTitle( JText::_('Member Birthday'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Member Birthday'),'reports.png');
        
		$this->assignRef('pagination', $paging);
        $this->assignRef('items',$data['items']);
        $this->assignRef('pr', $post);
        $this->assignRef('conditions', $conditions);
		$this->assignRef('task',$task);
               
        parent::display($tpl);
	
	}
    /*
     *  Windsor VIP Membership Statistic
     */     
    function displayMemberstatistic($tpl = null)
    {
    	$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.member', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));

        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
        $post = JRequest::get('post');
		//echo "<pre>";print_r($post);exit;
        /******** Sex ********/
        $extra_sex     = $mainframe->getUserStateFromRequest( $context.$view.'extra_sex','extra_sex','','array' );              
        $lists['extra_sex'] = JHTML::_('wrd.listSex','extra_sex[]',  $extra_sex);
        
        /******** Age ********/
        $extra_age     = $mainframe->getUserStateFromRequest( $context.$view.'extra_age','extra_age','','array' );              
        $lists['extra_age'] = JHTML::_('wrd.listAges','extra_age[]',  $extra_age);              
        
        /******** Title - Position ********/
        $extra_position     = $mainframe->getUserStateFromRequest( $context.$view.'extra_position','extra_position','','array' );              
        $lists['extra_position'] = JHTML::_('wrd.listPosition','extra_position[]',  $extra_position);
        
        /******** District ********/
        $extra_district     = $mainframe->getUserStateFromRequest( $context.$view.'extra_district','extra_district','','array' );              
        $lists['extra_district'] = JHTML::_('wrd.listDistricts','extra_district[]',  $extra_district);
        
        
        /******** Statistic by ********/
        $statisticBy = $mainframe->getUserStateFromRequest( $context.$view.'statisitc_by','statisitc_by','','string' );              
        $lists['statistic_by'] = $statisticBy;
        
        $conditions = array();
        
		$conditions['date_from'] = $post['date_from'];
		$conditions['date_to'] = $post['date_to'];
		if($post['date_from'] != ""){
			
			$conditions['date_from'] .= " 00:00:00";
		}
		else {
		
			$conditions['date_from'] = "";
		}
		if($post['date_to'] != ""){
			
			$conditions['date_to'] .= " 23:59:59";
		}
		else {
		
			$conditions['date_to'] = "";
		}
		
		
		$conditions['statistic_by'] = $statisticBy;
        $conditions['sex'] = (!empty($extra_sex) ? "'".trim(implode("','",$extra_sex),',')."'" : '');
        $conditions['age'] = (!empty($extra_age) ? trim(implode(',',$extra_age),',') : '');
        $conditions['job'] = (!empty($extra_position) ? trim(implode(',',$extra_position),',') : '');
        $conditions['location'] = (!empty($extra_district) ? trim(implode(',',$extra_district),',') : '');
        
        /******** Export excel: Member Statistic ********/
        if($task == 'exmemberstatistic')
        {                        
            $params = 'st='.$conditions['statistic_by'];
            $params .= '&f='.$conditions['date_from'];
			$params .= '&t='.$conditions['date_to'];
			$params .= '&s='.$conditions['sex'];
            $params .= '&a='.$conditions['age'];
            $params .= '&j='.$conditions['job'];
            $params .= '&l='.$conditions['location'];
            
            header('Location: '.JURI::root().'/exmemberstatistic.php?'.$params);            
        }
        else if($task == 'exmemberstatisticfilter')
        {                        
            $params = 'st='.$conditions['statistic_by'];
			$params .= '&f='.$conditions['date_from'];
			$params .= '&t='.$conditions['date_to'];
            $params .= '&s='.$conditions['sex'];
            $params .= '&a='.$conditions['age'];
            $params .= '&j='.$conditions['job'];
            $params .= '&location='.$conditions['location'];
            $params .= '&l='.(intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));

            header('Location: '.JURI::root().'/exmemberstatisticfilter.php?'.$params);            
        }
        
        if($task == 'memberstatisticfilter')
        {
            $items      = $model->memberStatisticFilter($conditions);   
            $paging     = $model->getPaging($items['total']);   
            $items      = $items['items'];
            $this->assignRef('pagination', $paging);
        }
        else{
            $items = $model->memberStatistic($conditions);    
        }
        
        /********* SET DATA *********/
        $document->setTitle( JText::_('Windsor VIP Membership Club').' - '. JText::_('PTD - Member Statistic'));        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Windsor VIP Membership Club').' - '. JText::_('PTD - Member Statistic'),'reports.png');
       
        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $conditions);
        $this->assignRef('task',    $task);
               
        parent::display($tpl);
    }
    
    /*
     *  Windsor VIP Membership Club
     */     
    function displayMembershipclub($tpl = null)
    {
    	$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.membership', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
    	
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();

        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
    
        $extra_status     = $mainframe->getUserStateFromRequest( $context.$view.'extra_status','extra_status','','string' );              
        $lists['extra_status'] = JHTML::_('wrd.listFieldExtraStatus','extra_status', $extra_status );

        $conditions = array();
        $conditions['extra_status'] = $extra_status; 

        if($pr['date_from'] != '') { 
        	$datefrom = explode('-', $pr['date_from']); 
        }
        else {
            $datefrom[0] = date('Y');
            $datefrom[1] = date('m');
            $datefrom[2] = '01';
        }
        if($pr['date_to'] != '') { 
        	$dateto = explode('-', $pr['date_to']); 
        }
        else {
            $dateto[0] = date('Y', time());
            $dateto[1] = date('m', time());
            $dateto[2] = date('d', time());
        }
        
       
        if($task == 'exmembershipclub')
        {                        
            $params = 'f='.implode('-', $datefrom).'&t='.implode('-', $dateto).'&s='.$extra_status;
            header('Location:'.str_replace('/administrator', '', JURI::base()).'/exmembershipclub.php?'.$params);
        }
        else if($task == 'exmembershipclubdetail')
        {                        
            $limit = (intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));  
            $params = 'f='.implode('-', $datefrom).'&t='.implode('-', $dateto).'&l='.$limit.'&s='.$extra_status;
            header('Location: '.str_replace('/administrator', '', JURI::base()).'exmembershipclubdetail.php?'.$params);
        }
        
        /********* SET DATA *********/
        $document->setTitle( JText::_('Windsor VIP Membership Club') );        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Windsor VIP Membership Club'),'reports.png');  
        $lists['date'] = 'Date: from <span>'.$pr['date_from'].'</span> to <span>'.$pr['date_to'].'</span>.';
        
        /********* Assign *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('pr',    $pr);
        
        /****** View detail ******/
        if($task == 'membershipclubdetail')
        {
            $tpl = 'detail';
            $datefrom[0] = array('from'=>$datefrom[0], 'to'=>$dateto[0]);
            $datefrom[1] = array('from'=>$datefrom[1], 'to'=>$dateto[1]);
            $datefrom[2] = array('from'=>$datefrom[2], 'to'=>$dateto[2]);
            
            $query      = $model->membershipclubdetail($datefrom[1], $datefrom[0], $datefrom[2], $conditions);
            $items      = $query['items'];
			$paging     = $model->getPaging($query['total']);
			$m_outlet = &JModelLegacy::getInstance('outlets','WrdModel');
			$outlet = $m_outlet->getList($condition = 'and cid = 01');	
            
            /********* Addition Assign *********/
			$this->assignRef('outlet',$outlet);
			$this->assignRef('total',$query['total']);
            $this->assignRef('pagination',    $paging);
        }
        else
        {
            $timeDateFrom = mktime(0, 0, 0, $datefrom[1], $datefrom[2], $datefrom[0]);
            $timeDateTo = mktime(0, 0, 0, $dateto[1], $dateto[2], $dateto[0]);
            $items = array();
            if($timeDateFrom <= $timeDateTo)
            {
            	$start = new DateTime($datefrom[0].'-'.$datefrom[1].'-'.$datefrom[2]);
            	$end = new DateTime($dateto[0].'-'.$dateto[1].'-'.$dateto[2]);
                $interval = new DateInterval("P1M");
                
                $period = new DatePeriod($start,$interval,$end);
                foreach($period as $dt){
                	$curyear = $dt->format("Y");
                	$curmonth = $dt->format("m");
                	
                	$key = mktime(0, 0, 0, $curmonth, 1,$curyear);
                	$items[date('M.Y', $key)] = $model->membershipClub($curmonth, $curyear);
                }
                
            }
        }
        /********* RENDER *********/       
        parent::display($tpl);
    }
    
    /*
     *  Member Pending Report Detail
     */     
    function displayMemberpendingreportdetail($tpl = null)
    {
    	$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.revenue', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
    	
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        $model    = &$this->getModel();
        
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
        
        
        
        /******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        
        
        /******** Fields display ********/
        $filter_field     = $mainframe->getUserStateFromRequest( $context.$view.'filter_field','filter_field','','array' );              
        $lists['filter_field'] = JHTML::_('wrd.listFieldReportDetail','filter_field[]', $filter_field );
        
        
        /******** Sort by ********/
        $extra_sort_by     = $mainframe->getUserStateFromRequest( $context.$view.'extra_sort_by','extra_sort_by','','string' );              
        $lists['extra_sort_by'] = JHTML::_('wrd.listFieldReportSortBy','extra_sort_by', $extra_sort_by );
        
        
        /******** Outlet ********/
        if($task == 'exmemberspendingreportdetail')
        {                        
            $limit = (intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));
            $filter_field = implode(',', $filter_field);
            $filter_field = trim($filter_field, ',');   
                     
            $filter_pick_up_outlet_extra = implode(',', $filter_pick_up_outlet);
            $filter_pick_up_outlet_extra = trim($filter_pick_up_outlet_extra, ',');            
            
            $params = 'f='.$pr['date_from'].'&t='.$pr['date_to'].'&l='.$limit.'&o='.$filter_pick_up_outlet_extra.'&sort='.$extra_sort_by;           
            header('Location:'.JURI::root().'/erevenuereportdetail.php?'.$params);
            //exit;
        }
        
        $conditions = array();
        $conditions['displayfields'] = $filter_field; 
        $conditions['outlet'] = $filter_pick_up_outlet; 
        $conditions['extra_sort_by'] = $extra_sort_by; 
        
        /********* GET ITEMS *********/
        if($pr['date_from'] != '') { $datefrom = $pr['date_from'].' 00:00:00'; }
        if($pr['date_to'] != '') { $dateto = $pr['date_to'].' 23:59:59'; }
        
        $items      = $model->revenuePendingReportDetail(1, $datefrom, $dateto, $conditions);
        $paging     = $model->revenuePendingReportDetail(0, $datefrom, $dateto, $conditions);
        $paging     = $model->getPaging($paging);        
        
        
        /********* SET DATA *********/
        if($pr['date_from'] == '' && $pr['date_to'] == '')
        {
            $lists['date'] = explode(' ', $items[0]->date_receipt);
            $lists['date'] = 'Date: from <span>'.$lists['date'][0].'</span> to now';
        }
        else if($pr['date_from'] == '' && $pr['date_to'] != '')
        {
            $lists['date'] = explode(' ', $items[0]->date_receipt);
            $lists['date'] = 'Date: from <span>'.$lists['date'][0].'</span> to <span>'.$pr['date_to'].'</span>';
        }
        else if($pr['date_from'] != '' && $pr['date_to'] == '')
        {
            $lists['date'] = 'Date: from <span>'.$pr['date_from'].'</span> to now';
        }
        else 
        {
            $lists['date'] = 'Date: from <span>'.$pr['date_from'].'</span> to <span>'.$pr['date_to'].'</span>';
        }
        
        /********* SET DATA *********/
        $document->setTitle( JText::_('Member Spending Reports Detail') );        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Member Spending Reports Detail'),'reports.png');
        
        
        /********* Rebuild filter fields *********/        
        
        if(($filter_field[0] != '') || ($filter_field[1] != ''))
        {   
            $filter_field_rebuild = array(
                'totalvisit' => '',
                'service' => '',
                'cover' => '',
                'food' => '',
                'beverage' => '',
                'other' => '',                
                'vat' => '',
                'averagespending' => '',
                 'foodratio' => '',
                'bvratio' => '',
                'miscratio' => '',
                'date_receipt' => ''
            );
            
            $size = count($filter_field);
            for($i=0; $i<$size; $i++)
            {
                switch($filter_field[$i])
                {
                    case 'cover':           $filter_field_rebuild['cover'] = 1;    break;
                    case 'food':            $filter_field_rebuild['food'] = 1;    break;
                    case 'beverage':        $filter_field_rebuild['beverage'] = 1;    break;
                    case 'other':           $filter_field_rebuild['other'] = 1;    break;
                    case 'vat':             $filter_field_rebuild['vat'] = 1;    break;
                    case 'averagespending': $filter_field_rebuild['averagespending'] = 1;    break;
                    
                    case 'foodratio':       $filter_field_rebuild['foodratio'] = 1;    break;
                    case 'bvratio':         $filter_field_rebuild['bvratio'] = 1;    break;
                    case 'miscratio':       $filter_field_rebuild['miscratio'] = 1;    break;
                    case 'totalvisit':      $filter_field_rebuild['totalvisit'] = 1;    break;
                    case 'service':         $filter_field_rebuild['service'] = 1;    break;
                }
            }
        }
        else
        {
            $filter_field_rebuild = array(
                'cover' => 1,  'food' => 1,  'beverage' => 1,  'other' => 1,                
                'vat' => 1,     'averagespending' => 1,   'foodratio' => 1,   'bvratio' => 1,
                'miscratio' => 1, 'date_receipt' => '', 'totalvisit' => 1, 'service' => 1
            );
        }
        if($extra_sort_by == 'outlet')
        {
            $filter_field_rebuild['date_receipt'] = 1;
        }
        
        
        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('pagination',    $paging);
        $this->assignRef('filter_field',    $filter_field_rebuild);
               
        parent::display($tpl);
    }
    
    /*
     *  Member Pending Report Summary 
     */     
    function displayMemberpendingreportsum($tpl = null)
    {
    	$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.revenue', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
    	
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        
        /********* GET DATA FROM DATABASE *********/
        $model    = &$this->getModel();

        $lists['order']         = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
        $lists['order_Dir']     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
        
        /******** Outlet ********/
        $filter_field     = $mainframe->getUserStateFromRequest( $context.$view.'filter_field','filter_field','','array' );              
        $lists['filter_field'] = JHTML::_('wrd.listFieldReport','filter_field[]', $filter_field );
       
        /******** Check if export to excel ********/
        if($task == 'exmemberspendingreportsum')
        {                        
            $limit = (intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));
            $filter_field = implode(',', $filter_field);
            $filter_field = trim($filter_field, ',');
            $params = 'f='.$pr['date_from'].'&t='.$pr['date_to'].'&l='.$limit.'&o='.$filter_field;           
            header('Location: '.JURI::root().'/erevenuereport.php?'.$params);
        }
                
        $conditions = array();
        $conditions['displayfields'] = $filter_field; 
        
        //get list items
        if($pr['date_from'] != '') { $datefrom = $pr['date_from'].' 00:00:00'; }
		else { $datefrom = date("Y-m")."-01"." 00:00:00";}
        if($pr['date_to'] != '') { $dateto = $pr['date_to'].' 23:59:59'; }
		else {$dateto = date("Y-m-d")." 23:59:59";}
        
        $items      = $model->revenuePendingReport(1, $datefrom, $dateto, $conditions);
        $paging     = $model->revenuePendingReport(0, $datefrom, $dateto, $conditions);
        $paging     = $model->getPaging($paging);        
        
        /********* SET DATA *********/
        $document->setTitle( JText::_('Outlets Revenue Reports ') );        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Outlets Revenue Reports'),'reports.png');
        
        /********* Rebuild filter fields *********/        
        if(($filter_field[0] != '') || ($filter_field[1] != ''))
        {   
            $filter_field_rebuild = array(
                'cover' => '',
                'food' => '',
                'beverage' => '',
                'other' => '',                
                'vat' => '',
                'averagespending' => '',
                
                'foodratio' => '',
                'bvratio' => '',
                'miscratio' => ''
            );
            
            $size = count($filter_field);
            for($i=0; $i<$size; $i++)
            {
                switch($filter_field[$i])
                {
                    case 'cover':           $filter_field_rebuild['cover'] = 1;    break;
                    case 'food':            $filter_field_rebuild['food'] = 1;    break;
                    case 'beverage':        $filter_field_rebuild['beverage'] = 1;    break;
                    case 'other':           $filter_field_rebuild['other'] = 1;    break;
                    case 'vat':             $filter_field_rebuild['vat'] = 1;    break;
                    case 'averagespending': $filter_field_rebuild['averagespending'] = 1;    break;
                    case 'foodratio':       $filter_field_rebuild['foodratio'] = 1;    break;
                    case 'bvratio':         $filter_field_rebuild['bvratio'] = 1;    break;
                    case 'miscratio':       $filter_field_rebuild['miscratio'] = 1;    break;
                }
            }
        }
        else
        {
            $filter_field_rebuild = array(
                'cover' => 1,  'food' => 1,  'beverage' => 1,  'other' => 1,                
                'vat' => 1,     'averagespending' => 1,   'foodratio' => 1,   'bvratio' => 1,
                'miscratio' => 1
            );
        }
        
        
        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('pagination',    $paging);
        $this->assignRef('filter_field',    $filter_field_rebuild);
               
        parent::display($tpl);
    }
     
    function displayMemberpendingreportsumTest($tpl = null){
    	
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');

        /********* GET DATA FROM DATABASE *********/
        $model    = &$this->getModel();

        $lists['order']         = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
        $lists['order_Dir']     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
        
        /******** Outlet ********/
        $filter_field     = $mainframe->getUserStateFromRequest( $context.$view.'filter_field','filter_field','','array' );              
        $lists['filter_field'] = JHTML::_('wrd.listFieldReport','filter_field[]', $filter_field );
       
        /******** Check if export to excel ********/
        if($task == 'excelpendinguser')
        {            
            $limit = (intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));
            $filter_field = implode(',', $filter_field);
            $filter_field = trim($filter_field, ',');
            $params = 'f='.$pr['date_from'].'&t='.$pr['date_to'].'&l='.$limit.'&o='.$filter_field;           
            header('Location: http://'.$_SERVER['SERVER_NAME'].'/erevenuereport.php?'.$params);
        }

        $conditions = array();
        $conditions['displayfields'] = $filter_field; 
        
        //get list items
        if($pr['date_from'] != '') { $datefrom = $pr['date_from'].' 00:00:00'; }
        if($pr['date_to'] != '') { $dateto = $pr['date_to'].' 23:59:59'; }
        
        $items      = $model->revenuePendingReport(1, $datefrom, $dateto, $conditions);
        $paging     = $model->revenuePendingReport(0, $datefrom, $dateto, $conditions);
        $paging     = $model->getPaging($paging);        
        
        /********* SET DATA *********/
        $document->setTitle( JText::_('Transaction Reports') );        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Membership Reports'),'reports.png');
        
        /********* Rebuild filter fields *********/
        $isCheckAll = implode(',', $filter_field);
        
        if($isCheckAll != '')
        {   
            $size = count($filter_field);
            $filter_field_rebuild = array(
                'vip_number' => '',
                'prefix' => '',
                'l_name' => '',
                'job' => '',                
                'company' => '',
                'email' => '',
                
                'phone' => '',
                'total_visit' => '',
                'pax' => '',
                'total' => '',                
                'liquor' => '',
                'food' => '',
                
                'beverage' => '',
                'other' => ''
            );
            for($i=0; $i<$size; $i++)
            {
                switch($filter_field[$i])
                {
                    case 'vip_number':  $filter_field_rebuild['vip_number'] = 1;    break;
                    case 'prefix':      $filter_field_rebuild['prefix'] = 1;    break;
                    case 'l_name':      $filter_field_rebuild['l_name'] = 1;    break;
                    case 'job':         $filter_field_rebuild['job'] = 1;    break;
                    case 'company':     $filter_field_rebuild['company'] = 1;    break;
                    case 'email':       $filter_field_rebuild['email'] = 1;    break;
                    case 'phone':       $filter_field_rebuild['phone'] = 1;    break;
                    case 'total_visit': $filter_field_rebuild['total_visit'] = 1;    break;
                    case 'pax':         $filter_field_rebuild['pax'] = 1;    break;
                    case 'total':       $filter_field_rebuild['total'] = 1;    break;
                    case 'liquor':      $filter_field_rebuild['liquor'] = 1;    break;
                    case 'food':        $filter_field_rebuild['food'] = 1;    break;
                    case 'beverage':    $filter_field_rebuild['beverage'] = 1;    break;
                    case 'other':       $filter_field_rebuild['other'] = 1;    break;
                }
            }
        }
        else
        {
            $filter_field_rebuild = array(
                'vip_number' => 1,  'prefix' => 1,  'l_name' => 1,  'job' => 1,                
                'company' => 1,     'email' => 1,   'phone' => 1,   'total_visit' => 1,
                'pax' => 1,         'total' => 1,   'liquor' => 1,  'food' => 1, 
                'beverage' => 1,    'other' => 1
            );
        }
        
        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('pagination',    $paging);
        $this->assignRef('lists',    $lists);
        $this->assignRef('filter_field',    $filter_field_rebuild);
               
        parent::display($tpl);
    }
        
    function displayGeneralreport($tpl = null){
    	$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.revenue', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
    	
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        
        
        /********* GET DATA FROM DATABASE *********/
        $model    = &$this->getModel();

        $lists['order']         = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
        $lists['order_Dir']     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
        
        /******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        
        /******** Check if export to excel ********/
        if($task == 'excelpendinguser')
        {            
            $limit = (intval($_POST['topDisplaytbx']) > 0 ? intval($_POST['topDisplaytbx']): intval($_POST['topDisplaySelect']));
            $filter_pick_up_outlet = implode(',', $filter_pick_up_outlet);
            $filter_pick_up_outlet = trim($filter_pick_up_outlet, ',');
            $params = 'f='.$pr['date_from'].'&t='.$pr['date_to'].'&l='.$limit.'&o='.$filter_pick_up_outlet;           
            header('Location: '.JURI::root().'eepu.php?'.$params);
        }
        
        $conditions = array();
        $conditions['outlet'] = $filter_pick_up_outlet; 
        
        //get list items
        if($pr['date_from'] != '') { $datefrom = $pr['date_from'].' 00:00:00'; }
		else { $datefrom = date("Y-m")."-01"." 00:00:00";}
        if($pr['date_to'] != '') { $dateto = $pr['date_to'].' 23:59:59'; }
        else {$dateto = date("Y-m-d")." 23:59:59";}
        
        $items      = $model->getTopMemberPending(1, $datefrom, $dateto, $conditions);
		$paging     = $model->getTopMemberPending(0, $datefrom, $dateto, $conditions);
		$paging     = $model->getPaging($paging);
		
        /********* SET DATA *********/
        $document->setTitle( JText::_('Transaction Reports') );        
        WrdHelper::addSubMenu($view,$this->getLayout());
        
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Membership Reports'),'reports.png');
        
        /********* RENDER *********/
        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('pagination',    $paging);
        $this->assignRef('lists',    $lists);
               
        parent::display($tpl);
    }
	
	function displayTransactionreport($tpl = null){
		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', 86400);
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.revenue', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
    	
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        
        /********* GET DATA FROM DATABASE *********/
        $model    = &$this->getModel();
        $lists['order']         = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
        $lists['order_Dir']     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
        
		/******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        $conditions = array();
        $conditions['outlet'] = $filter_pick_up_outlet; 
        
        if($conditions['outlet'][0] != ''){
			$conditions['outlet'] = implode(",",$conditions['outlet']);
		}
		else {
			$conditions['outlet'] = '';
		}
		
		if($pr['date_from'] != '') { 
			$conditions['dateFrom'] = $pr['date_from'].' 00:00:00'; }
        else 
        	$conditions['dateFrom'] = '';
        
        if($pr['date_to'] != '') { 
        	$conditions['dateTo'] = $pr['date_to'].' 23:59:59';}
        else 
        	$conditions['dateTo'] = '';
	
		/******** Check if export to excel ********/
        if($task == 'extransactionreport')
        {            
			$limit = intval($_POST['topDisplaySelect']);  
			$params = 'df='.$conditions['dateFrom'].'&dt='.$conditions['dateTo'].'&o='.$conditions['outlet'].'&l='.$limit;           
            header('Location: '.JURI::root().'extransactionreport.php?'.$params);
            exit;
        }
        $items      = $model->transactionreport($conditions); 
		$paging     = $model->getPaging($items["total"]);
        $document->setTitle( JText::_('Transaction Reports') );        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Transaction Reports'),'reports.png');

        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('pagination',   $paging);
        $this->assignRef('lists',    $lists);
               
        parent::display($tpl);
		
    }
    
	function displayTransactionreportweb($tpl = null){
		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', 86400);
		$user  = &JFactory::getUser();
    	if(!$user->authorise('wrd.report.revenue', 'com_wrd'))
    		return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
    	
        /********* INIT *********/
        $mainframe = &JFactory::getApplication();
        $document = & JFactory::getDocument();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $task = JRequest::getCmd('task');
        
        /********* GET DATA FROM DATABASE *********/
        $model    = &$this->getModel();
        $lists['order']         = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
        $lists['order_Dir']     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
        
        /******** Calendar ********/
        $pr = array() ;
        $pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
        $pr['date_to']     = $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
        
		/******** Outlet ********/
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','array' );              
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx','pick_up_at[]',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );

        $conditions = array();
        $conditions['outlet'] = $filter_pick_up_outlet; 
        if($conditions['outlet'][0] != ''){
		
			$conditions['outlet'] = implode(",",$conditions['outlet']);
		}
		else {
			$conditions['outlet'] = '';
		}
		
		if($pr['date_from'] != '') { $conditions['dateFrom'] = $pr['date_from'].' 00:00:00'; }
        else $conditions['dateFrom'] = '';
        if($pr['date_to'] != '') { $conditions['dateTo'] = $pr['date_to'].' 23:59:59';}
        else $conditions['dateTo'] = '';
	
		/******** Check if export to excel ********/
        if($task == 'extransactionreportweb')
        {            
			$limit = intval($_POST['topDisplaySelect']);  
			$params = 'df='.$conditions['dateFrom'].'&dt='.$conditions['dateTo'].'&o='.$conditions['outlet'].'&l='.$limit;           
            header('Location: '.JURI::root().'extransactionreportweb.php?'.$params);
            exit;
        }
        
        $items      = $model->transactionreportweb($conditions); 
		$paging     = $model->getPaging($items["total"]);
        $document->setTitle( JText::_('Transaction Reports for web') );        
        WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
        JToolBarHelper::title(JText::_('Transaction Reports Web'),'reports.png');

        $this->assignRef('lists',    $lists);
        $this->assignRef('items',    $items);
        $this->assignRef('pr',    $pr);
        $this->assignRef('pagination',   $paging);
        $this->assignRef('lists',    $lists);

        parent::display($tpl);
		
    }
	
    
    function displayExportexcel($tpl = null){
        parent::display($tpl);
    }
    
    function downloadFileExcel(){

        if($_SESSION['fileExcelImport'] != '')
        {        
            $fileName = $_SESSION['fileExcelImport'].'.xlsx';
            unset($_SESSION['fileExcelImport']);
            $_SESSION['fileExcelImport'] = '';

            $fullPath = JPATH_ROOT.DS.'transactions'.DS.$fileName;
            if( file_exists($fullPath) )
            {
                $fsize = filesize($fullPath);
                
                header("Pragma: public"); // required
                header("Expires: 0");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Cache-Control: private",false); // required for certain browsers
                header('Content-Type: application/vnd.ms-excel;');           
                header("Content-type: application/x-msexcel"); 
                header("Content-Disposition: attachment; filename=\"wmc.xlsx\";" );
                header("Content-Transfer-Encoding: binary");
                header("Content-Length: ".$fsize);
                ob_clean();
                flush();
                readfile( $fullPath );         
                die;
            }
        }
    }
    
  	function displayMembership($tpl = null){
  		
		$mainframe = &JFactory::getApplication();
		$document = & JFactory::getDocument();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
		$document->setTitle( JText::_('Membership Reports') );
		
		WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();
	    
		JToolBarHelper::title(JText::_('Membership Reports'),'reports.png');
		
		//pr = params
		$pr = array() ;
		$pr['date_from'] = $mainframe->getUserStateFromRequest( $context.$view.'date_from','date_from','','date' );
		$pr['date_to'] 	= $mainframe->getUserStateFromRequest( $context.$view.'date_to','date_to','','date' );
		$pr['filter_status'] = $mainframe->getUserStateFromRequest( $context.$view.'status_selection','status_selection',-1,'int' );
		
		$model	= &$this->getModel();
		//$pr['filter_status']
		switch($pr['filter_status']){
			case '1' : 
				$condition = ' and p.status_of_card = 1' ;
				break ;
			case '2' : 
				$condition = ' and p.pick_up_date != "0000-00-00"' ;
				break ;
		}
		
		//get list items
		$items	= $model->getListProfiles($pr['date_from'], $pr['date_to'], $condition , 0 ) ;
		$total	= $model->getListProfiles($pr['date_from'], $pr['date_to'], $condition , 1 ) ;
		$paging = $model->getPaging($total->total);
		
		$filter_order     		= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
		$filter_order_Dir 		= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
		
		$lists['order'] 		= $filter_order;
		$lists['order_Dir'] 	= $filter_order_Dir;
		$lists['listStatusSelection'] 	= JHTML::_('wrd.listStatusSelection','status_selection',$pr['filter_status']);
		
		$this->assignRef('lists',	$lists);
	    $this->assignRef('items',	$items);
	    $this->assignRef('pr',	$pr);
	   	$this->assignRef('pagination',	$paging);
	    
  		parent::display($tpl);
	}

	function displayRedemption($tpl = null){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
		$document = &JFactory::getDocument();
		$document->setTitle( JText::_('Gifts Redemption Reports') );

		JToolBarHelper::title(JText::_('Gifts Redemption Reports'),'gifts-reports.png');
 		
		JToolBarHelper::custom('send_redemp_notice_email','messaging','messaging','Send redemption notice email');
		JToolBarHelper::custom('send_redemp_pick_up_notice','messaging','messaging','Send redemption pick up notice email');
		
		WrdHelper::addSubMenu($view,$this->getLayout());
		$this->sidebar = JHtmlSidebar::render();

		$model = $this->getModel('reports') ; 
		$items = $model->getListRedemtion('',0) ;
		$p_details = array() ;
		$user_info = array() ;
		$p_o_u = array() ;
		$outlet_info = array() ;
		$redemption = array() ;
		if(count(items) > 0){
			foreach ($items as $r){
				$p_details[$r->product_id] = $this->getProductDetails($r->product_id) ;
				$user_info[$r->user_id] = WrdHelper::getUserProfile($r->user_id,'userid') ;
				$p_o_u[$r->user_id] = WrdHelper::getPoints($r->user_id) ;
				$outlet_info[$r->id] = $this->getOutletDetails($user_info[$r->user_id]->pick_up_at) ;
				$redemption[$r->id] = $this->getRedemptionDetails($r->id) ;
			}
		}
		
		$total = $model->getListRedemtion('', 1) ;
		$paging = $model->getPaging($total->total);
		$filter_order     	= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
		$filter_order_Dir 	= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
		$lists['order'] 	= $filter_order;
		$lists['order_Dir'] = $filter_order_Dir;

		$filter_product_id 	= $mainframe->getUserStateFromRequest( $context.$view.'product_id','product_id',-1,'int' );
		$lists['products'] 	= JHTML::_('wrd.listProducts','product_id',$filter_product_id,'onchange="this.form.submit()"');
		
		$filter_outlet 			= $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at',-1,'int' );
		$lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsP','pick_up_at',$filter_outlet,'onchange="this.form.submit()"','pick_up_at','','and pid != 00' );;
		
		$filter_status 			= $mainframe->getUserStateFromRequest( $context.$view.'status','status',-1,'int' );
		$lists['filter_status'] = JHTML::_('wrd.listRedemptionStatus','status',$filter_status,'onchange="this.form.submit()"','status','' );
		
		$filter_date_from 		= $mainframe->getUserStateFromRequest( $context.$view.'filter_date_from','filter_date_from','','date' );
		$filter_date_to 		= $mainframe->getUserStateFromRequest( $context.$view.'filter_date_to','filter_date_to','','date' );
		$filter_type 			= $mainframe->getUserStateFromRequest( $context.$view.'filter_type','filter_type',-1,'int' );
		$lists['filter_type'] 	= JHTML::_('wrd.listFilterTypeDate','filter_type',$filter_type,'onchange="this.form.submit()"','filter_type','' );
		$search 				= $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string' );
		
		$search 				= JString::strtolower( $search );
		
		$lists['search'] 		= $search;
		$this->assignRef('items',	$items) ;
		$this->assignRef('search',	$search) ;
		$this->assignRef('p_details',	$p_details) ;
		$this->assignRef('pagination',	$paging) ;
	    $this->assignRef('lists',	$lists) ;
	    $this->assignRef('redemption',	$redemption) ;
	    $this->assignRef('user_info',	$user_info) ;
		$this->assignRef('p_o_u',	$p_o_u) ;
		$this->assignRef('outlet_info',	$outlet_info) ;
		$this->assignRef('filter_date_from',	$filter_date_from) ;
		$this->assignRef('filter_date_to',	$filter_date_to) ;
	    parent::display($tpl);
  	}

	function getProductDetails($id){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_products WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs;
	}
	
	function getOutletDetails($id){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_outlets WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs;
	}
	function getRedemptionDetails($id){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_redemption re WHERE re.id ='.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs;
	}
}
?>